import React, { useEffect, useMemo } from 'react';
import { Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import { withRouter } from 'react-router-dom';
import styles from './index.less'

/**
 * 
 * @param {func} click 按钮点击事件 参数type 按钮类型 
 * @param {array} filterTypes 选填 过滤渲染按钮 
 */
const RenderButtom = props => {
  const { dispatch, click, global, filterTypes = [2] } = props
  const { menus } = global

  useEffect(() => {
    dispatch({
      type: 'global/saveData',
      payload: {
        btns: getCurrentBtn(menus)
      }
    })
  }, [])

  const clearModalData = (type) => {
    dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: {}
      }
    })
    click(type)
  }

  const getCurrentBtn = menu => {
    const path = props.location.pathname
    return menu
            .map(i => i.path == path ? i.button : getCurrentBtn(i.children || []))
            .filter(i => i && i.length != 0)
            .reduce((acc, val) => acc.concat(val), []);
  }

  //  当没有查询按钮时 默认页面table数据不显示 （页面配置尚未完成 目前没有该功能）
  // localStorage.setItem('hasSearchBtn', getCurrentBtn(menus).filter(e => e.type == 2).length > 0)
  localStorage.setItem('hasSearchBtn', true)

  // 查询按钮额外放置 type 2 查询
  return menus.length > 0 && getCurrentBtn(menus)
    .filter(e => !filterTypes.includes(e.type))
    .map(b => b.type == 4 ?
      // 删除按钮
      <Popconfirm
        title="是否确定删除?"
        onConfirm={clearModalData.bind(this, b.type)}
        onCancel={() => console.log('cancel')}
        okText="确定"
        cancelText="取消"
        key={`del-${b.id}`}
      >
        <Button type="primary" className={styles.gap}>{b.name}</Button>
      </Popconfirm> :
      <Button type="primary" className={styles.gap} key={b.id} onClick={click.bind(this, b.type)}>{b.name}</Button>)
};

export default connect(({ global, role }) => ({
  global,
  role,
}))(withRouter(RenderButtom));
